package Command;

import java.util.Vector;

import DTO.Row;
import XML.XMLHelper;
public class Update extends Command {
	
	public Update(String str) 
	{
		super(str); 
	}
	
	public Object executeQuery()
	{		 
		Object ret = null;
		String sql = getSql();
		
		// Check update keyword				
		String str1 = sql.trim();
		if(str1.startsWith("update"))
		{
			int tableIndex = sql.indexOf("update") + "update".length();
			String[] strs = sql.substring(tableIndex).trim().split(" ", 2);
			String tableName = strs[0];
			
			if(strs.length > 1)
			{
				String str2 = strs[1].trim();
				
				if(str2.startsWith("set"))
				{
					int columnsIndex = str2.indexOf("set") + "set".length();
					int endColumnsIndex = str2.indexOf("where");
					
					if(endColumnsIndex > -1)
					{
						String columns = str2.substring(columnsIndex, endColumnsIndex);
						String condition = str2.substring(endColumnsIndex + "where".length());
						Vector<Row> updateRows = Condition.ReversePoland(condition, getDbName(),  tableName);
						System.out.println("update row size : " + updateRows.size());
						
						String[] columnToUpdate = columns.split(",");
						Vector<String> fieldToUpdate = new Vector<String>();
						Vector<Object> valToUpdate = new Vector<Object>();
						Vector<Integer> valType = new Vector<Integer>();
						for(int i = 0 ; i < columnToUpdate.length; i++)
						{
							String[] fieldAndVal = Condition.getOperandsAndOperator(columnToUpdate[i]);
							
							if(fieldAndVal != null && fieldAndVal[1] == "=")
							{
								fieldToUpdate.add(fieldAndVal[0]);
								if(fieldAndVal[2].startsWith("'") && fieldAndVal[2].lastIndexOf("'") > 0)
								{
									valType.add(1);
									valToUpdate.add(fieldAndVal[2].substring(0, fieldAndVal[2].lastIndexOf("'")));
								}
								else
								{
									valType.add(0);
									valToUpdate.add(fieldAndVal[2]);
								}
							}
						}
						
						if(XMLHelper.UpdateRow(getDbName(), tableName, fieldToUpdate, valToUpdate,  valType, updateRows))
							ret = "Update " + updateRows.size() + " row(s) successful";
						else
							ret = "Update failed!";
					}
					
				}
			}
			
		}
		
		return ret;
	}
}
